# !/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : 大野
import json

from common.database import DataBase
from common.db_config import DB_Config
import interface.common.utils as util
from loguru import logger
import time
from common.timeJson import ComplexEncoder
import re

db = DataBase()
dbc = DB_Config()


def case_db(project_id, case_sql):
    '''
    操作操作数据库
    :param project_id: 项目id
    :param case_sql: 用例SQL
    :return:
    '''
    global data
    time.sleep(2)
    logger.info(f"执行SQL{case_sql}")
    sql = f'select pi.project_code,pi.db_host,pi.db_port,pi.db_name,pi.db_username,pi.db_password from ' \
          f'project_env_info pi,project_info pf where pi.project_name = pf.project_name and pf.id = {project_id} '
    try:
        db_conn = db.test_platform([sql])
        db_conns = db_conn[0]
        db_password = util.decryption(db_conns["db_password"], db_conns["project_code"])
        db_conns.update({"db_password": str(db_password)})
        conn = dbc.db_common(db_conns)
        logger.info(f"用例SQL》》{type(case_sql)}=={case_sql}")
        if '|,|' in case_sql:
            sql = case_sql.split("|,|")
            logger.info(f"用例校验执行多条SQL：{sql}")
            for i in sql:
                if re.search('select', i, re.IGNORECASE):
                    data = db.executeSql(conn, [i], m='r')
                    logger.info(f"执行结果：{data}")
                else:
                    data = db.executeSql(conn, [i], m='w')
            return data
        else:
            logger.info(f"用例校验执行单条SQL：{case_sql}")
            if re.search('select', case_sql, re.IGNORECASE):
                data = db.executeSql(conn, [case_sql], m='r')
                logger.info(f"{case_sql}单条执行结果：{data}")
                return data
            else:
                data = db.executeSql(conn, [case_sql], m='w')
                logger.info(f"{case_sql}单条执行结果：{data}")
                return data
    except Exception as e:
        return {"dbsuccess": "false", "dbresponse": str(e)}
